package com.zikao.common.service.impl;/**
 * Created by My on 2021-04-11.
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zikao.common.service.RedisService;
import com.zikao.common.utils.MyMessage;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: Likaisheng
 * @Description:
 * @Date: Created in 18:32:50 2021-04-11
 * @Modified By:
 */
@Service("redisService")
@Data
@Slf4j
public class RedisServiceImpl implements RedisService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public List<MyMessage> getMessges(String key) {
        List<MyMessage> messages = new LinkedList<>();
        SetOperations<String, String> operations = redisTemplate.opsForSet();
        Set<String> members = operations.members(key);
        List<MyMessage> messageList = members.stream().map(r -> {
            MyMessage message = JSONObject.parseObject(r, MyMessage.class);
            return message;
        }).collect(Collectors.toList());
        log.info("members:"+members.toString());
        messages.addAll(messageList);
        return messages;
    }

    @Override
    public void sendMessage(MyMessage message) {
        SetOperations<String, String> operations = redisTemplate.opsForSet();
        operations.add(message.getReceiverEmail(),JSON.toJSONString(message));
        log.info("message:"+JSON.toJSONString(message));
    }

    @Override
    public void delMessage(String key,MyMessage message) {
        SetOperations<String, String> operations = redisTemplate.opsForSet();
        operations.remove(key,JSON.toJSONString(message));
    }
}
